package com.moli.lumpSugar.user.service.impl;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;

import com.moli.lumpSugar.common.annotation.RedissonLock;
import com.moli.lumpSugar.common.domain.enums.IdempotentEnum;
import com.moli.lumpSugar.common.domain.enums.YesOrNoEnum;
import com.moli.lumpSugar.user.dao.UserBackpackDao;
import com.moli.lumpSugar.user.domain.entity.UserBackpack;
import com.moli.lumpSugar.user.service.IUserBackpackService;
import org.apache.commons.lang3.ObjectUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @program: LumpSugarChat
 * @description:
 * @author: zhangjt
 * @create: 2024-10-25 10:19
 **/
@Service
public class IUserBackpackServiceImpl implements IUserBackpackService {
    @Autowired
    private UserBackpackDao userBackpackDao;
    @Autowired
    @Lazy
    private IUserBackpackServiceImpl userBackpackService;
    @Override
    public void acquireItem(Long uid, Long itemId, IdempotentEnum idempotentEnum, String businessId) {
        // 组装幂等值
        String idempotentValue = getIdempotentValue(idempotentEnum, businessId,itemId);
        // 因为要调用本方法，而本方法是事务方法，所以要使用代理对象，所以得注入自身
        userBackpackService.doAcquireItem(uid, itemId, idempotentValue);
    }

    @Transactional
    @RedissonLock(key = "#idempotentValue", waitTime = 5000)
    public void doAcquireItem(Long uid, Long itemId,String idempotentValue){
        // 查询数据库，判断是否已经领取过该物品
        UserBackpack userBackpack = userBackpackDao.getByIdempotent(idempotentValue);
        if (ObjectUtil.isNotNull(userBackpack)){
            return;
        }
        // 领取物品
        userBackpackDao.save(new UserBackpack(null, uid, itemId, YesOrNoEnum.NO.getStatus(), idempotentValue, null, null));
    }

    private String getIdempotentValue(IdempotentEnum idempotentEnum, String businessId, Long itemId) {
        return itemId + "_" + idempotentEnum.getType() + "_" + businessId;
    }
}
